import { yzPay } from "../../../utils/yz_pay"; //引入支付方法
import diyBackGround from "./componet/diyBackGround";
import payKeyboard from "components/payKeyboard";
import _, { stubTrue } from "lodash";
import newCouponList from "./componet/new_couponList";
import invoicePop from "../../goods/components/invoice-pop.vue";
import yzAddressList from "components/ui_components/yz_addressList/index";
export default {
  mixins: [yzPay],
  data() {
    return {
      credit2: 0,
      buttons: [],
      typename: "",
      recharge: "",
      ordersn: "",
      money: "",
      diymoney: '',//自定义输入的金额
      diy_money_index: null,
      activatDes: {},
      priceDifferencePool: false,
      tagBalance: false,

      // 选择的充值方式
      pay_type: "",
      // 余额字样
      balanceLang: this.fun.getBalanceLang(),
      diyname: "",
      isOpenCmc: false, //首次需要验证是否开启cmc
// 新充值接口页面内容,后续插件跟商城余额充值页面优化也用这套
      activity_new: [],
      buttons_new: [],
      display_switch_new: [],
      plugins_new: [],
      //优惠券
      store_id: "",
      member_coupon_ids: "",
      member_coupon_list: [],
      recharge_new: null, //	充值记录
      couponShowPopup: false,
      coupon_size: 0, //选择了几张优惠券

      popupSpecs: false,
      plugin_name: "",
      recharge_double: "",
      show: false,
      point: null,
      city:null,
      stroeList: [],
      storeNameKey: "",
      //详细地址
      full_address: "",
      page: 1,
      total_page: 0,
      // 发票数据
      invoice_list:{},
      addressList_caller: "", //地址组件调用着，识别是地址调用还是发票插件调用
      showAddress: false,

      need_sign: false,
      sign_info: {},
      min_recharge: null,//最低起充金额
      diy_amount: [],//自定义充值金额

      plugin_code: {},//插件名，用于处理不同的插件充值逻辑，如果后续有多个插件同时使用，可以用逗号隔开
      bottom_content: null,
      top_img: null
    };
  },

  computed: {
    coupon_size_c() {
      if (!this.member_coupon_ids) {
        return "请选择优惠券";
      }
      let array_a = this.member_coupon_ids.split(",");
      return `已选择${array_a.length}张`;
    },
    discountType(num) {
      return num => {
        num = num ? num : 0;
        if (this.activatDes.proportion_status == 0) {
          return num + "元";
        } else {
          return num + "%";
        }
      };
    },
    plugin_Main_style() {
      if (this.$route.params.plugin == "store_oil_station") {
        return "margin-top:0;";
      }
      return "";
    },
    throttledMoneyChange() {
      return _.debounce(this.moneyChange, 300); // 500毫秒内只执行一次
    }
  },
  methods: {
    // 增加/修改地址
    confirmSelectAddress(item) {
      if (this.addressList_caller == "invoice") {
        this.$refs.invoicePop.setAddress(item);
        this.showAddress = false;
      }
      this.addressData = item;
    },
    //发票插件显示地址
    invoiceShowAddressFun() {
      this.yzAddressListOptions = {
        is_open_store_delivery: this.is_open_store_delivery,
        selected: this.selected
      };
      this.addressList_caller = "invoice";
      this.showAddress = true;
    },
    tapStoreID(item) {
      this.store_id = item.id;
      this.full_address = item.full_address;
      if(item.diy_amount.length > 0){
        this.diy_amount = item.diy_amount;
      }
      if (item.activity.length != 0) {
        const index = this.activity_new.findIndex(ele => ele.code === "store-oil-station");
        if (index !== -1) {
          this.activity_new[index] = item.activity;
        } else {
          this.activity_new.push(item.activity);
        }
      } else {
        this.activity_new = this.activity_new.filter(ele => ele.code !== "store-oil-station");
      }
      this.showClose();
    },
    getMoreData(e){
      this.getStoreList(e,true)
    },
    async getStoreList($event,key = false) {
      let json = {
        lng: this.point.lng,
        lat: this.point.lat,
        city: this.city,
        name: this.storeNameKey
      };
      if(key){
        this.page = this.page + 1;
        json.page = this.page;
      }
      let { data, msg, result } = await $http.post("plugin.store-oil-station.frontend.oil-store.index", json, "");
      if (result) {
        console.log(data);
        if(key){
          this.stroeList = this.stroeList.concat(data.data);
          return
        }
        this.page = 1;
        this.total_page = data.last_page;
        if (!this.total_page) this.total_page = 1;
        this.stroeList = data.data;
        this.show = true;
      } else {
        if(key){
          this.page = this.page - 1;
          return
        }
        this.$toast(msg);
      }
    },
    // 发票组件回传数据
    subInvoice(e) {
      console.log(e,'发票组件回传数据')
      this.invoice_list = e;
      this.moneyChange();
    },
    tapinvoicePop() {
      console.log(this.plugins_new.balance_invoice);
    },
    onSearch() {
      console.log("eeeeeeeeeeeee");
    },
    //新优惠券组装json信息
    assembleCoupons_new(arr) {
      // 使用 map() 直接获取id数组，然后 join() 方法将其连接成字符串
      return arr.map(item => item.id).join(",");
    },
    childSelectCoupon(e) {
      this.member_coupon_ids = this.assembleCoupons_new(e);
      this.moneyChange();
    },
    // 门店列表选择关闭
    showClose() {
      this.moneyChange();
      this.show = false;
      this.page = 1;
      this.total_page = 1;
      this.stroeList = [];
      this.storeNameKey = "";
    },
    async moneyChange() {
      if (!this.money) return; //为空不走接口
      let obj = this.plugins_new[this.$route.params.plugin];
      if (!obj.preApi) return;
      let json = {};
      for (const key in obj.preParams) {
        json[key] = this[obj.preParams[key]] ? this[obj.preParams[key]] : null;
      }
      let { data, msg, result } = await $http.post(obj.preApi, json, "");
      if (result) {
        this.member_coupon_list = data.member_coupon_list;
        this.recharge_new = data.recharge;
      } else {
        this.$toast(msg);
      }
    },
    couponShow() {
      this.couponShowPopup = true;
    },
    // 初始化参数
    async getData() {
      let url = "finance.balance.balance";
      let json = {};
      if (this.priceDifferencePool) {
        url = "plugin.price-difference-pool.frontend.modules.pool.controllers.recharge.page";
      } else if (this.tagBalance) {
        url = "plugin.tag-balance.frontend.recharge.page";
      } else if (this.$route.name == "YccRecharge") {
        url = "plugin.ycc-money.frontend.recharge.index";
      } else if (this.$route.params.plugin == "store_oil_station") {
        url = "finance.balance-recharge.page";
        await this.fun.getLocation('定位中').then(res => {
          console.log(res);
          json.city = res.city;
          json.lng = res.point?.lng;
          json.lat = res.point?.lat;
          this.point = res.point || {};
          this.city = res.city;
        });
        json.plugin = this.$route.params.plugin;
      }
      if (this.fun.isCPS() && this.fun.isCPSAPPI()) {
        json.wechat_app_pay_type = "cps";
      }

      $http.get(url,json).then(
        (response)=> {
          if (response.result == 1) {
            this.need_sign = response.data.need_sign;//是否需要签署合同
            this.sign_info = response.data.sign_info || {};//合同信息
            if (this.$route.params.plugin == "store_oil_station") {
              this.credit2 = response.data.credit2;
              this.activity_new = response.data.activity;
              this.buttons_new = response.data.buttons;
              this.buttons = this.buttons_new;
              this.display_switch_new = response.data.display_switch;
              this.plugins_new = response.data.plugins;
              this.full_address = this.plugins_new?.store?.full_address;
              this.recharge = 1;
              if (this.plugins_new.store) {
                this.store_id = this.plugins_new.store.id;
              }
              if (this.plugins_new.balance_invoice) {
                this.$refs.invoicePop.initData(this.plugins_new.balance_invoice);
              }
              if (this.plugins_new?.store_oil_station?.diy_amount.length > 0){
                this.diy_amount = this.plugins_new?.store_oil_station?.diy_amount;
              }
              return;
            }
            if(this.priceDifferencePool){
              let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
              this.diyname = basic_info.price_difference_pool_name?basic_info.price_difference_pool_name:'资金池';
              this.credit2 = response.data.pool;
              this.buttons = response.data.buttons;
              this.recharge = 1;
              return;
            }
            if(this.tagBalance){
              this.diyname = response.data.tag?.tag_name;
              this.credit2 = response.data.balance;
              this.buttons = response.data.button;
              this.typename = '充值';
              this.recharge = 1;
              return;
            }
            if(this.$route.name == 'YccRecharge'){
              this.balanceLang = '余额';
              this.credit2 = response.data.plugin_member.amount;
              this.recharge = 1;
              this.buttons = response.data.payment_list;
              this.plugin_name = response.data.plugin_name;
              this.recharge_double = response.data.recharge_double;
              return;
            }
            this.diy_amount = response.data?.diy_amount||[];
            this.min_recharge = response.data.min_recharge || null;
            this.credit2 = response.data.credit2;
            this.buttons = response.data.buttons;
            this.typename = response.data.typename;
            this.recharge = response.data.recharge;
            this.activatDes = response.data.remark;
            this.plugins_new = response.data.plugins;
            this.bottom_content = response.data.bottom_content;
            this.top_img = response.data.top_img;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        });
    },
    async priceDifferencePool_confirm(type){
      let json ={
        pay_id:type,
        amount:this.money
      }
      let url = 'plugin.price-difference-pool.frontend.modules.pool.controllers.recharge.apply';
      await $http.get(url, json).then(response=>{
        if(response.result == 1){
          this.rechargePay({
            pay_type: type,
            data: response,
            ordersn: response.data.order_sn,
            type: 'price-difference-pool'
          });
        }else{
          this.$dialog.alert({ message: response.msg });
        }
      });
    },
    // YCC资产插件使用商城支付类型需要order_pay_id,后端定的流程
    getMergaPay(ids, btn) {
      $http
        .get("order.merge-pay", { order_ids: ids }, "加载中")
        .then(response => {
          if (response.result === 1) {
            this.order_pay_id = response.data.order_pay.id;
            this.uid = response.data.order_pay.uid;
            if (btn.other.need_password) {
              this.popupSpecs = true;
              return;
            }
            this.confirm(btn);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getVerifyPassword(pwd){
      $http.get("payment.password.check", { password: pwd }, "").then(
        (response) => {
          if (response.result == 1) {
            // console.log('密码正确')
            // ycc资产充值 走商城余额支付
            this.balancePay(pwd,'','')
            this.changePopupSpecs();
          } else {
            this.$dialog
              .confirm({ message: response.msg })
              .then(() => {
                if (response.data.code == 2001) {
                  // 商城支付密码设置未开启
                  // this.$router.go(-1)
                } else if (response.data.code == 2002) {
                  // 用户未设置支付密码
                  // 去设置密码
                  this.$router.push(this.fun.getUrl("set_balance_password", {}));
                } else if (response.data.code == 2003) {
                  // 支付密码错误,重新输入
                  this.payarr = "";
                  this.changePopupSpecs();
                }
              })
              .catch(() => {
                if (response.data.code == 2001) {
                  // 商城支付密码设置未开启
                } else if (response.data.code == 2002) {
                  // 用户未设置支付密码
                } else if (response.data.code == 2003) {
                  // 支付密码错误
                }
              });
          }
        });
    },
    // 安全键盘组件
    onInput(e){
      this.getVerifyPassword(e);
    },
    changePopupSpecs(e) {
      this.popupSpecs = false;
    },
    yccConfirm(type, btn) {
      console.log(btn.other.need_password, "dddddddd");
      $http.get("plugin.ycc-money.frontend.create.index", { ycc_money_price: this.money }).then(response => {
        if (response.result == 1) {
          this.getMergaPay(response.data.order_ids, btn);
        } else {
          this.$dialog.alert({ message: response.msg });
        }
      });
    },
    toSignV2(){
      this.$router.push(this.fun.getUrl("shopSignIndexV2",{scene: 7}));//余额充值签署合同
    },
    toSignDetail(){
      this.$router.push(this.fun.getUrl("signPage",{id: this.sign_info.contract_id}));//查看合同
    },
    // 确认充值
    confirm_post(type,btn) {
      if(this.need_sign){
        this.$dialog.confirm({
          title: '温馨提示',
          confirmButtonText: '去签署',
          message: `根据平台要求，您需完成《${this.sign_info.contract_name}》合同签署后再充值${this.balanceLang}！`,
        })
          .then(() => {
            return this.$router.push(this.fun.getUrl("shopSignIndexV2",{scene: 7}));//余额充值签署合同
          })
          .catch(() => {});
        return;
      }

      if(this.priceDifferencePool){
        this.priceDifferencePool_confirm(type);
        return;
      }

      if(this.diymoney) this.money = this.diymoney;
      this.pay_type = type;
      if (!this.money || this.money <= 0) {
        this.$dialog.alert({ message: "输入值不能小于0" });
        return;
      }
      if (type == 202006 && !this.isOpenCmc) {
        this.isHaveCmcInfo();
        return;
      }
      this.money = parseFloat(this.money);
      // ycc资产充值
      if (this.$route.name == "YccRecharge") {
        this.yccConfirm(type, btn);
        return;
      }
      let url = "finance.balance.recharge"; // "&client_type=2&app_type=wechat"
      if (this.tagBalance) {
        url = "plugin.tag-balance.frontend.recharge.index";
      }
      if (window.isMiniprogram) {
        url += "&client_type=2&app_type=wechat";
      }
      let _json = {
        pay_type: this.pay_type,
        recharge_money: this.money
      };
      if (this.recharge_new) {
        _json.recharge_money = this.recharge_new.actual_pay;
      }
      if (this.member_coupon_ids) {
        _json.member_coupon_ids = this.member_coupon_ids;
      }
      if (this.store_id) {
        _json.store_id = this.store_id;
      }
      if(this.$route.params.plugin == "store_oil_station"){
        let obj = this.plugins_new[this.$route.params.plugin];
        for (const key in obj.preParams) {
          _json[key] = this[obj.preParams[key]] ? this[obj.preParams[key]] : null;
        }
      }

      //判断this.plugin_code是否有值，有_json添加plugin_code属性，并把this.plugin_code对象里的值赋给它，用逗号隔开
      if(this.plugin_code){
        for (const key in this.plugin_code) {
          if(key&&this.plugin_code[key]) {
            _json.plugin_code = this.plugin_code[key];
          }
        }
      }

      $http.post(url, _json, "正在充值").then(response => {
        if (response.result == 1) {
          if (this.pay_type == "88") {
            this.$dialog.alert({ message: "充值成功" }).then(() => {
              this.$router.go(-1);
            });

            return;
          }
          if (this.fun.isTextEmpty(response.data.ordersn) && this.pay_type != "140" && this.pay_type != "132") {
            this.$dialog.alert({ message: "参数错误" });
            return false;
          }
          this.ordersn = response.data.ordersn;
          let keyOption = this.tagBalance ? "tagRecharge" : "balance";
          this.rechargePay({
            pay_type: this.pay_type,
            data: response,
            ordersn: this.ordersn,
            type: keyOption
          });
        } else {
          this.$dialog.alert({ message: response.msg });
          if (this.pay_type == 101) {
            if (response.data.eplus_bind_mobile == 1) {
              // 绑定手机
              this.$dialog
                .alert({
                  message: response.msg
                })
                .then(() => {
                  this.$router.push(this.fun.getUrl("wisdomBind", { option: "phone", to: "pay" }));
                });
            }
          }
        }
      });
    },
    isHaveCmcInfo() {
      $http.get("plugin.cmc-pay.frontend.account.get-cmc-account", {}, "").then(response => {
        if (response.result === 1) {
          this.isOpenCmc = true;
          this.confirm_post(202006);
        } else {
          this.$dialog.alert({ message: "没有CMC账号！" });
          this.$router.push(this.fun.getUrl("cmcPayInfo", {}));
        }
      });
    },
    selectActivityNum(num){
      this.money = num;
      this.diy_money_index = this.diy_amount.length;
      this.diymoney = num;
    },
    selectDiyNum(num){
      if (this.$route.params.plugin == "store_oil_station") {
        this.diy_money_index = num;
        this.diymoney = '';
        this.money = this.diy_amount[num]?.amount?this.diy_amount[num]?.amount:'';
        return
      }
      this.diy_money_index = num;
      this.diymoney = '';
      this.money = this.diy_amount[num];
    },
    selectPlugBtn(name,code){
      this.$set(this.plugin_code,name,code);
    },
  },
  activated() {
    window.scrollTo(0, 0);
    if (this.$route.name == "balance_rechargepdp") {
      //price-difference-pool 插件的充值页 复用样式
      this.priceDifferencePool = true;
    }
    if (this.$route.name == "balance_rechargeTag") {
      console.log("tag-balance复用样式");
      this.tagBalance = true;
    }
    console.log(this.$route);
    this.pay_type = "";
    this.money = "";
    if (this.$route.params.num) {
      this.money = this.$route.params.num;
    }
    this.getData(); // 初始化参数
  },
  components: { diyBackGround, payKeyboard, newCouponList, invoicePop,yzAddressList }
};
